<template>
    <div>
        <h2>G6 脑图树布局示例</h2>
        <div ref="container" style="width:100%;height:400px;background:#f5f5f5;"></div>
    </div>
</template>
<script setup lang="ts">
defineOptions({ name: 'AntvG6MindMap' });
import { ref, onMounted } from 'vue';
import { Graph, treeToGraphData } from '@antv/g6';

const container = ref();

const getNodeSide = (graph: any, datum: any) => {
    const parentData = graph.getParentData(datum.id, 'tree');
    if (!parentData) return 'center';
    return datum.style.x > parentData.style.x ? 'right' : 'left';
};

onMounted(async () => {
    // 获取数据
    const res = await fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json');
    const data = await res.json();

    const graph = new Graph({
        container: container.value,
        autoFit: 'view',
        data: treeToGraphData(data),
        node: {
            style: {
                labelText: (d: any) => d.id,
                labelBackground: true,
                labelPlacement: function (d: any) {
                    const side = getNodeSide(this, d);
                    return side === 'center' ? 'right' : side;
                },
                ports: [{ placement: 'right' }, { placement: 'left' }],
            },
            animation: {
                enter: false,
            },
        },
        edge: {
            type: 'cubic-horizontal',
            animation: {
                enter: false,
            },
        },
        layout: {
            type: 'mindmap',
            direction: 'H',
            getHeight: () => 32,
            getWidth: () => 32,
            getVGap: () => 4,
            getHGap: () => 64,
        },
        behaviors: ['collapse-expand', 'drag-canvas', 'zoom-canvas'],
    });

    graph.render();
});
</script> 